const initialState = {
  cartList:JSON.parse(localStorage.getItem("cart"))||[],
  totalCount:0,
  allSelect:false
};

 export function cartReducer(state=initialState,action){
   switch(action.type){
     case "ADDCART":
       //去重
       var flag = false;//默认购物车中无该商品
       state.cartList.forEach((element)=>{
         if(element._id===action.item._id){
           flag = true;
           element.count+=1;
         }
       })

       if(!flag){
         action.item.count = 1;
         action.item.checked = false;
         state.cartList.push(action.item)
       }

       localStorage.setItem("cart",JSON.stringify(state.cartList));
       return {
        cartList:state.cartList,
        totalCount:state.totalCount,
        allSelect:state.allSelect
       };
     case "CHANGEITEMSTATUS":
       //找到将要修改状态的商品
       state.cartList.forEach((element)=>{
         if(element._id===action.item._id){
           element.checked = action.item.checked;
         }
       })

       //同步全选状态
       //数组中所有的 元素 都必须满足条件，every返回true，否则返回false
       var result = state.cartList.every((element)=>{
          return element.checked === true;
       })
       state.allSelect = result;


       //就算总价和总量
       state.totalCount = 0;
       state.cartList.forEach((element)=>{
         if(element.checked){
          state.totalCount+=element.count
         }
       })

       return {
        cartList:state.cartList,
        totalCount:state.totalCount,
        allSelect:state.allSelect
       }
     case "ALLSELECT":
       state.allSelect = action.boolean;
       //同步每一个商品的选中状态
       state.cartList.forEach((element)=>{
          element.checked = action.boolean;
       })

       //就算总价和总量
       state.totalCount = 0;
       state.cartList.forEach((element)=>{
         if(element.checked){
          state.totalCount+=element.count
         }
       })

       return {
         cartList:state.cartList,
         totalCount:state.totalCount,
         allSelect:state.allSelect
       };
     default:
       return state;
   }
  return state;
}